// packageA/pages/cashService/admin/login/login.js
const { imgPath } = require('../../../../utils/request')
const { request } = require('../../../../utils/request');
const { encryptSM2 } = require('../../../../utils/sm-crypto');
const { hexMD5 } = require('../../../../utils/md5');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgPath: imgPath,
    captchaData: {},
    type: '',

    username: '',
    password: '',
    captcha: '',
    phone: '',
    smsCaptcha: '',

    loginDisable: false,

    btnText: '获取验证码',
    btnDisable: false,
    timeout: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('type',options.type)
    this.setData({ type: options.type })
    if (options.type == 'admin') {
      wx.setNavigationBarTitle({
        title: '管理员登录'
      })
    } else if (options.type == 'superadmin') {
      wx.setNavigationBarTitle({
        title: '会计登录'
      })
    }

    this.fetchCaptcha()
  },
  onShow: function (options) {
    this.fetchCaptcha()
    console.log(wx.getStorageSync('userInfo').loginType,this.data.type )
    if (wx.getStorageSync('userInfo').loginType == 2 && this.data.type=='admin' ) {
      wx.redirectTo({
        url: '/pages/cashService/admin/personManage/personManage',
      })
    }else if (wx.getStorageSync('userInfo').loginType == 5 && this.data.type=='admin'){
      wx.redirectTo({
        url: '/pages/cashService/third/admin/personManage/personManage',
      })
    }else if(wx.getStorageSync('userInfo').loginType == 3 && this.data.type=='admin'){
      wx.redirectTo({
        url: '/pages/cashService/admin/personManage/personManage',
      })
    }
  },
  /**
   * 获取图片验证码
   */
  fetchCaptcha() {
    request('/smsk/wechat/auth/captchaw150h30', 'GET').then(res => {
      this.setData({
        captchaData: res.data.data
      })
    })
  },

  /**
   * 获取短信验证码
   */
  fetchSmsCaptcha() {
    // 校验表单
    if (!this.validForm()) {
      return
    }
    // 拼装参数
    let query = {
      idNum: this.data.username,
      phone: this.data.phone,
      captchaId: this.data.captchaData.captchaId,
      captcha: this.data.captcha
    }
    request('/smsk/wechat/auth/sms', 'POST', query).then(res => {
      console.log(res.data)
      if (res.data.code == 0) {
        wx.showToast({
          title: '短信发送成功',
          icon: 'success'
        })
        this.setData({
          btnDisable: true,
          timeout: 60
        })
        this.btnCountDown()
      } else {
        this.showToast(res.data.message)
        this.fetchCaptcha()
      }
    })
  },
  /**
   * 修改短信发送按钮状态
   */
  btnCountDown() {
    if (this.data.timeout === 0) {
      this.setData({
        btnDisable: false,
        btnText: '获取验证码'
      })
    } else {
      this.setData({
        btnText: '重新发送(' + this.data.timeout + ')'
      })
      setTimeout(() => {
        this.setData({
          timeout: this.data.timeout - 1,
        })
        this.btnCountDown()
      }, 1000)
    }
  },

  /**
   * 点击“登录”
   */
  login() {
    // 表单校验
    if (!this.validForm('login')) {
      return
    }
    // 防止重复点击
    if (this.data.loginDisable) {
      return
    }
    this.setData({ loginDisable: true })
    // 拼装参数
    let loginData = {
      username: this.data.username,
      password: encryptSM2(this.data.password, this.data.captchaData.publicKey),
      captcha: this.data.captcha,
      captchaId: this.data.captchaData.captchaId,
      phone: this.data.phone,
      smsCaptcha: this.data.smsCaptcha
    }
    wx.showLoading({
      title: '登录中',
    })
    let that = this
    request('/smsk/wechat/auth/adminlogin', 'POST', loginData).then(res => {
      console.log(res.data.data)
      wx.hideLoading()
      if (res.data.code == 0) {
        wx.setStorageSync('token', res.data.data.token)
        wx.setStorageSync('userInfo', res.data.data)
        if (res.data.data.loginType == 2 ) {
          wx.redirectTo({
            url: '/pages/cashService/admin/personManage/personManage',
          })
          wx.hideToast()
        } else if (res.data.data.loginType == 3 ) {
          wx.redirectTo({
            url: '/pages/cashService/admin/personManage/personManage',
          })
          wx.hideToast()
        }else if(res.data.data.loginType == 5){ //清分公司管理员
          wx.redirectTo({
            url: '/pages/cashService/third/admin/personManage/personManage',
          })
          wx.hideToast()
        }
      } else if(res.data.code === 13) {
        wx.showModal({
          title: '提示',
          content: res.data.message,
          confirmText: "去重置",
          success (res) {
            if (res.confirm) {
              that.setData({ 
                loginDisable: false,
                password: '',
                captcha: '',
                captchaId: '',
                smsCaptcha: ''
              })
              that.go2ResetPwd()
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      } else {
        this.setData({ loginDisable: false })
        this.showToast(res.data.message)
        this.fetchCaptcha()
      }
    })
  },

  /**
   * 表单校验
   */
  validForm(str) {
    if (!this.data.username) {
      if (this.data.type == 'admin') {
        this.showToast('请填写管理员账号')
      } else if (this.data.type == 'superadmin') {
        this.showToast('请填写会计账号')
      }
      return false
    }
    if (!this.data.password) {
      this.showToast('请填写密码')
      return false
    }
    if (!this.data.phone || !(/^1[345789]\d{9}$/.test(this.data.phone))) {
      this.showToast('请填写正确的手机号')
      return false
    }
    if (!this.data.captcha || !(this.data.captchaData.hashCode == hexMD5(this.data.captcha.toUpperCase()))) {
      this.showToast('请填写正确的图片验证码')
      return false
    }
    if (str == 'login') {
      if (this.data.smsCaptcha.length != 6) {
        this.showToast('请填写正确的短信验证码')
        return false
      }
    }
    return true
  },

  /**
   * 简化弹出
   */
  showToast(msg) {
    wx.showToast({
      title: msg,
      icon: 'none'
    })
  },
  go2ResetPwd(){
    wx.navigateTo({
      url: '/pages/cashService/resetPwd/index',
    })
  }

})